
package com.hxrk.aidlservice;

import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;

import com.hxrk.cecardvr.AudioUtil;
import com.hxrk.cecardvr.CamParameter;
import com.hxrk.cecardvr.CamService;
import com.hxrk.cecardvr.CopyFileUtil;
import com.hxrk.cecardvr.LogUtils;
import com.hxrk.cecardvr.MyApplication;
import com.hxrk.cecardvr.Utils;
import com.hxrk.cecardvr.appmanager.AppManager;
import com.hxrk.cecardvr.appmanager.OnPackagedObserver;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import static com.hxrk.cecardvr.MyApplication.TAG;
import static com.hxrk.cecardvr.MyApplication.mContext;
import static com.hxrk.cecardvr.MyApplication.mDvrManager;
import static com.hxrk.cecardvr.Utils.putTextCPHM;

public class ServiceBinder extends CarDVRListener.Stub {

    public CamParameter getChanncl(int id) {
        try {
            for (int i = 0; i < CamService.camParameters.length; i++) {
                Log.d("lyj","CamService.camParameters["+i+"] imgType:"+CamService.camParameters[i].IMG_TYPE +" devtype:"+CamService.camParameters[i].DEV_TYPE+" id:"+id);
                if (CamService.camParameters[i].IMG_TYPE == CamParameter.FMT_TYPE_H264) {
                    if ( id == CamParameter.DEV_TYPE_MIPI ) {
                        if( CamService.camParameters[i].DEV_TYPE == CamParameter.DEV_TYPE_MIPI)
                            return CamService.camParameters[i];
                    }else if(id == CamParameter.DEV_TYPE_USB){
                        if( CamService.camParameters[i].DEV_TYPE == CamParameter.DEV_TYPE_USB)
                            return CamService.camParameters[i];
                    }
                }
            }
            return null;
        }catch (Exception e){
            LogUtils.e(TAG, "getChanncl 异常！！！！！");
            return null;
        }
    }

    private static boolean copyalarm = false;
    private static boolean lasta = false;
    @Override
    public void doCarInfo(Bundle mBundle) throws RemoteException {
        try {
            Bundle bundle = mBundle;
            if (bundle != null) {
                String CarPlaNum = bundle.getString("CarPlaNum");
                Utils.putTextSpeed = bundle.getInt("CarSpeed");
                Utils.longitude = bundle.getDouble("longitude", 0);
                Utils.latitude = bundle.getDouble("latitude", 0);
                Utils.accZT = bundle.getInt("ACCZT");
                Utils.simNo = bundle.getString("zdsim");
                if (Utils.accZT == 1) {
                    CamService.isACC = true;
                }

                int ptType = bundle.getInt("PTType", 1);
                if (ptType != CamService.PTType){
                    CamService.PTType = ptType;
                    MyApplication.editor.putInt("PTType", CamService.PTType);
                    MyApplication.editor.commit();
                }


                if (!putTextCPHM.equals(CarPlaNum)) {
                    putTextCPHM = CarPlaNum;
                    MyApplication.editor.putString("TextCPHM", putTextCPHM);
                    MyApplication.editor.commit();
                }
                putTextCPHM = bundle.getString("CarPlaNum");
                //LogUtils.i(TAG, "CarInfo putTextCPHM = " + putTextCPHM + "   putTextSpeed = " + Utils.putTextSpeed + "   longitude = " + Utils.longitude + "   latitude = " + Utils.latitude + "   accZT = " + Utils.accZT + "   PTType = " + CamService.PTType);
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doCarInfo异常！！！！");
        }
    }

    @Override
    public void doAccOpen() throws RemoteException {
        LogUtils.i(TAG, "doAccOpen");
        CamParameter mipiCamPr = getChanncl(2);
        mipiCamPr.setMipiRecordState(true);
        /*CamService.isACC = true;
        CamService.isRTSP = false;
        CamService.isAlarm = false;

        MyApplication.editor.putBoolean("ISACC", true);
        MyApplication.editor.commit();

        // 打开USB电源
        Utils.writeUSBPowerFile(1);*/
    }

    @Override
    public void doAccClose() throws RemoteException {
        LogUtils.i(TAG, "doAccClose");

        CamParameter mipiCamPr = getChanncl(2);
        mipiCamPr.setMipiRecordState(false);
        /*CamService.isACC = false;
        CamService.isRTSP = false;
        CamService.isAlarm = false;

        MyApplication.editor.putBoolean("ISACC", false);
        MyApplication.editor.commit();

        CamService.closeVideo();
        // 关闭USB摄像头电源
        Utils.writeUSBPowerFile(0);*/
    }

    @Override
    public void doPhoto(Bundle mBundle) throws RemoteException {
        try {
            if (mBundle != null) {
                int ChannclID = mBundle.getInt("ChannclID", 0);
                int PZJG = mBundle.getInt("PZJG", 0);
                int PZZS = mBundle.getInt("PZZS", 1); //拍摄张数
                int Cause = mBundle.getInt("Cause", -1); //拍照原因
                int PTTYPE = mBundle.getInt("PTTYPE", CamService.PTType);
                String temp_file = mBundle.getString("temp_file", ""); //拍照原因
                ArrayList<Integer> mMedias = new ArrayList<Integer>();
                for (int i = 0; i < PZZS; i++) {
                    if (ChannclID > -1) {
                        int mediaID = MyApplication.GetMediaID();
                        mMedias.add(mediaID);
                        Bundle bundle = new Bundle(mBundle);
                        bundle.putInt("MediaID", mediaID);
                        bundle.putInt("MediaType", 0);
                        bundle.putInt("MediaCode", 0);
                        bundle.putInt("EventCode", 0);
                        bundle.putInt("PTTYPE", PTTYPE);
                        bundle.putIntegerArrayList("mMedias", mMedias);

                        LogUtils.e("jpegcallback1", "开始拍照 MediaID  " + bundle.getInt("MediaID"));
                        if (ChannclID == 12) {
                            CamParameter campr1 = getChanncl(1);
                            CamParameter campr2 = getChanncl(2);
                            if (campr1 != null && campr2 != null) {
                                CamService.isRTSP = true;
                                if (campr1.DEV_TYPE == CamParameter.DEV_TYPE_MIPI || campr2.DEV_TYPE == CamParameter.DEV_TYPE_MIPI )
                                    CamService.lRTSPTime = System.currentTimeMillis();

                                String filename = campr1.saveJpgFile(putTextCPHM, mediaID, Cause, 1);
                                bundle.putString("FilePath", filename);
                                campr2.saveJpgFile(putTextCPHM, mediaID, Cause, 2);
                                MyApplication.photoBundles.put(mediaID, bundle);
                            } else {
                                // 通道不支持
                                bundle.putInt("Result", 2);
                                mDvrManager.mDvrCallBack.doPhoto(bundle);
                            }
                        } else {
                            CamParameter campr = getChanncl(ChannclID);
                            if (campr != null) {
                                CamService.isRTSP = true;
                                if (campr.DEV_TYPE == CamParameter.DEV_TYPE_MIPI)
                                    CamService.lRTSPTime = System.currentTimeMillis();
                                if (temp_file.isEmpty()) {
                                    String filename = campr.saveJpgFile(putTextCPHM, mediaID, Cause, 0);
                                    bundle.putString("FilePath", filename);
                                    MyApplication.photoBundles.put(mediaID, bundle);
                                } else {
                                    //临时文件存在则不进行抓拍
                                    File file = new File(temp_file);
                                    if (file.exists()) {
                                        String filename = campr.getjpgfilename(mediaID, Cause, 0);
                                        CopyFileUtil.copyFile(temp_file, filename, false);
                                        file.delete();
                                        bundle.putString("FilePath", filename);
                                        bundle.putInt("Result", 0);
                                    } else
                                        bundle.putInt("Result", 2);
                                    MyApplication.mDvrManager.mDvrCallBack.doPhoto(bundle);
                                }
                            } else {
                                // 通道不支持
                                bundle.putInt("Result", 2);
                                mDvrManager.mDvrCallBack.doPhoto(bundle);
                            }
                        }
                    }
                    try {
                        Thread.sleep(PZJG * 1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doPhoto异常！！！！！");
        }
    }

    @Override
    public void doVedio(Bundle mBundle) throws RemoteException {
        try {
        }catch (Exception e){
            LogUtils.e(TAG, "doVedio异常！！！！！");
        }
        final Bundle bundle = new Bundle(mBundle);
        if (bundle != null && !bundle.isEmpty()) {
            final int ChannclID = mBundle.getInt("ChannclID", 0);
            final int PZJG = bundle.getInt("PZJG");
            int PTTYPE = mBundle.getInt("PTTYPE", CamService.PTType);

            final int LSH = bundle.getInt("LSH", -1);
            if (LSH != -1)
                bundle.putInt("LSH", -1);

            final CamParameter campr = getChanncl(ChannclID);
            if (campr != null) {
                CamService.isRTSP = true;

                //停止当前录像
                campr.saveStart = 0;

                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            campr.CMDBundle = bundle;
                            if (PZJG == 0)
                                Thread.sleep(60 * 1000);
                            else
                                Thread.sleep(PZJG * 1000);

                            LogUtils.d("doVedio  LSH = " + LSH);
                            campr.CMDBundle.putInt("LSH", LSH);
                            //停止
                            campr.saveStart = 0;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }

    @Override
    public void doVedioEnd(Bundle mBundle) throws RemoteException {
        try {
        }catch (Exception e){
            LogUtils.e(TAG, "doVedioEnd异常！！！！！");
        }
        LogUtils.e("doVedioEnd", "doVedioEnd");
        int ChannclID = mBundle.getInt("ChannclID", 0);
        CamParameter campr = getChanncl(ChannclID);
        if (campr != null) {
            //停止当前录像
            campr.saveStart = 0;
        }
    }

    /**
     * 录像回放控制
     * @param bundle
     * @throws RemoteException
     */
    @Override
    public void doVedio_playbackEnd(Bundle bundle) throws RemoteException {

//        LogUtils.e("doVedio_playbackEnd","doVedio_playbackEnd");
//
//        int ChannelId = bundle.getInt("ChannclID", -1);
//        int CSKZ = bundle.getInt("CSKZ",-1);
//        int KJKT_BS = bundle.getInt("KJKT_BS",-1);
//        String TDHFWZStr = bundle.getString("TDHFWZStr");
//
//        if(ChannelId == 1 || ChannelId == 2){
//            ChannelId -= 1;
//        }
//
//        //暂停或停止
//        if (CSKZ == 1 || CSKZ == 2){
//            CamService.isSendServer_record[ChannelId] = false;
//            CamService.isSend120a[ChannelId] = false;
//        }else if (CSKZ == 0){
//            CamService.isSendServer_record[ChannelId] = true;
//            CamService.isSend120a[ChannelId] = true;
//        }


    }

    public class AudioLoop extends Thread {

        public Bundle bundle;
        public AudioUtil audio = new AudioUtil();
        public int LYSJ = 0;

        public AudioLoop(Bundle b) {
            bundle = b;
        }

        @Override
        public void run() {
            try {
                LYSJ = bundle.getInt("LYSJ");
                audio.startRecord();
                audio.recordData();
                if (LYSJ == 0)
                    LYSJ = 1200;
                int tik = 0;
                while (tik < LYSJ) {
                    Thread.sleep(1000);
                    tik++;
                }
                audio.stopRecord();
                audio.convertWaveFile();

                bundle.putInt("MediaID", audio.mediaID);
                bundle.putInt("MediaType", 1);
                bundle.putInt("MediaCode", 3);
                bundle.putInt("EventCode", 0);
                bundle.putString("FilePath", audio.outFileName);
                File file = new File(audio.outFileName);
                if (file.exists()){
                    bundle.putInt("FileLength", (int)file.length());
                }
                mDvrManager.mDvrCallBack.doAudio(bundle);
//                // 保存多媒体信息在数据库
//                mDvrManager.mDvrCallBack.AddMediaEx(bundle);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static AudioLoop[] audioLoops = new AudioLoop[3];

    @Override
    public void doAudioEnd(Bundle mBundle) throws RemoteException {
        try {
            int Cause = mBundle.getInt("Cause", 0);  //录音原因
            if (Cause >= 0 && Cause < 3 && audioLoops[Cause] != null) {
                audioLoops[Cause].LYSJ = 0;
                audioLoops[Cause].wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doAudio(Bundle mBundle) throws RemoteException {
        try {
            final Bundle bundle = mBundle;
            if (bundle != null && !bundle.isEmpty()) {
                int Cause = bundle.getInt("Cause", 0);  //录音原因
                if (Cause >= 0 && Cause < 3) {
                    try {
                        if (audioLoops[Cause] != null) {
                            audioLoops[Cause].LYSJ = 0;
                            audioLoops[Cause].wait();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    audioLoops[Cause] = new AudioLoop(bundle);
                    audioLoops[Cause].start();
                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doAudio异常！！！！！");
        }
    }

    @Override
    public void doShell(Bundle mBundle) throws RemoteException {
        try {
            if (mBundle != null && !mBundle.isEmpty()) {
                String cmd = mBundle.getString("cmd");
                LogUtils.e("doShell cmd = " + cmd);
                try {
                    Utils.execCommand(cmd);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doShell异常！！！！！");
        }
    }

    @Override
    public void doVedio9501(Bundle mBundle) throws RemoteException {
        try {
            Bundle bundle = mBundle;
            Log.d("lyj", "doVedio9501 -----------------0");
            if (bundle != null && !bundle.isEmpty()) {
                String ServerIP = bundle.getString("ServerIP");
                int TCP_PORT = bundle.getInt("TCP_PORT");
                int UDP_PORT = bundle.getInt("UDP_PORT");
                int channelId = bundle.getInt("ChannclID");
                int PTTYPE = bundle.getInt("PTTYPE", CamService.PTType);
                int dataType = bundle.getInt("DATATYPE");
                int codeStreamType = bundle.getInt("STREAMTYPE");
                byte[] Cmd1209 = mBundle.getByteArray("Cmd1209");
                int is1078 = mBundle.getInt("is1078");
                CamParameter campr = getChanncl(channelId);
                Log.d("lyj", "doVedio9501 -----------------channelId:"+channelId);
                if (campr != null) {
                    Log.d("lyj", "doVedio9501 -----------------2");
                    LogUtils.e("initRTP", "initRTP");
                    CamService.isRTSP = true;
                    if (campr.DEV_TYPE == CamParameter.DEV_TYPE_MIPI){
                        CamService.lRTSPTime = System.currentTimeMillis();
                        campr.sendMipiData = true;
                    }

                    campr.initRTP(ServerIP, TCP_PORT, UDP_PORT, dataType, codeStreamType, Cmd1209, PTTYPE,is1078);

                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doVedio9501异常！！！！！");
        }
    }

    @Override
    public void doVedio9102(Bundle mBundle) throws RemoteException {
        try {
            Bundle bundle = mBundle;
            if (bundle != null && !bundle.isEmpty()) {

                int channelId = bundle.getInt("ChannclID");
                int KZZL = bundle.getInt("KZZL");
                int YSPLX = bundle.getInt("YSPLX");
                int MLLX = bundle.getInt("MLLX");
                Log.d("lyj","doVedio9102 ---------------------channelId:"+channelId);
                CamParameter campr = getChanncl(channelId);
                if (campr != null) {
                    Log.d("lyj","doVedio9102");
                    campr.sendMipiData = false;
                    campr.ctrlRTP(KZZL, YSPLX, MLLX);
                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doVedio9102异常！！！！！");
        }
    }

    @Override
    public void doVedio9509(Bundle mBundle) throws RemoteException {
        try {
            Bundle bundle = mBundle;
            if (bundle != null && !bundle.isEmpty()) {
                String ServerIP = bundle.getString("ServerIP");
                int TCP_PORT = bundle.getInt("TCP_PORT");
                int UDP_PORT = bundle.getInt("UDP_PORT");
                int channelId = bundle.getInt("ChannclID");
                int PTTYPE = bundle.getInt("PTTYPE", CamService.PTType);
                int KJKT = bundle.getInt("KJKT");
                int dataType = bundle.getInt("DATATYPE");
                int codeStreamType = bundle.getInt("STREAMTYPE");
                String FileName = bundle.getString("FileName");
                byte[] Cmd1209 = mBundle.getByteArray("Cmd1209");
                int is1078 = mBundle.getInt("is1078");
                CamParameter campr = getChanncl(channelId);
                if (campr != null) {
                    Log.e("lyj", "doVedio9509: come in");
                    campr.initfileRTP(ServerIP, TCP_PORT, UDP_PORT, dataType, KJKT, codeStreamType, FileName, Cmd1209, PTTYPE,is1078);
                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doVedio9509异常！！！！！");
        }
    }

    @Override
    public void doVedio950A(Bundle mBundle) throws RemoteException {
        try {
            Bundle bundle = mBundle;
            if (bundle != null && !bundle.isEmpty()) {
                int channelId = bundle.getInt("ChannclID");
                int CSKZ = bundle.getInt("CSKZ");
                int KJKT_BS = bundle.getInt("KJKT_BS");
                String TDHFWZStr = bundle.getString("TDHFWZStr");
                CamParameter campr = getChanncl(channelId);
                if (campr != null) {
                    campr.ctrlfileRTP(CSKZ, KJKT_BS, TDHFWZStr);
                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doVedio950A异常！！！！！");
        }
    }

    @Override
    public void doCopyFile(Bundle mBundle) throws RemoteException {
        try {
            if (mBundle != null && !mBundle.isEmpty()) {
                String strfile = mBundle.getString("srcfile");
                String destfile = mBundle.getString("destfile");
                String sdcards = Utils.getPath2();
                if (!sdcards.isEmpty()) {
                    CopyFileUtil.copyFile(strfile, destfile, true);
                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doCopyFile异常！！！！！");
        }
    }

    @Override
    public void doDisplay() throws RemoteException {

    }

    @Override
    public void doUnDisplay() throws RemoteException {

    }

    @Override
    public String doRealVideo(Bundle mBundle) throws RemoteException {
        return null;
    }

    @Override
    public void doRealVideoEnd(Bundle mBundle) throws RemoteException {

    }

    // 程序安装回调
    OnPackagedObserver installCallBack = new OnPackagedObserver() {
        String result = "";
        Bundle bundle = new Bundle();
        @Override
        public void packageInstalled(String packageName, int returnCode) {
            if (returnCode == 1){
                result = "安装成功";
            }else {
                result = "安装失败";
            }
            LogUtils.i(MyApplication.TAG, result);

            try {
                Utils.execCommand("reboot");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void packageDeleted(String packageName, int returnCode) {
            result = "卸载结果 = " + packageName + "---" + returnCode;
            LogUtils.i(MyApplication.TAG, result);
            try {
                bundle.putString("result", result);
                MyApplication.mDvrManager.mDvrCallBack.installResult(bundle);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void doInstallApp(Bundle mBundle) throws RemoteException {
        Bundle bundle = mBundle;
        if (bundle != null && !bundle.isEmpty()) {
            // 程序类型
            int type = bundle.getInt("type");
            // apk文件路径
            String akpPath = bundle.getString("apkPath");
            boolean isreboot = false;

            try {
                AppManager appManager = new AppManager(mContext);
                appManager.setOnPackagedObserver(installCallBack);
                // 安装apk
                appManager.installPackage(akpPath);
            } catch (NoSuchMethodException e) {
                isreboot = true;
                LogUtils.i(MyApplication.TAG, "安装异常");
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                isreboot = true;
                LogUtils.i(MyApplication.TAG, "安装异常");
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                isreboot = true;
                LogUtils.i(MyApplication.TAG, "安装异常");
                e.printStackTrace();
            }

            if (isreboot){
                File file = new File(akpPath);
                if (file.exists())
                    file.delete();

                try {
                    Utils.execCommand("reboot");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void doUnInstallApp(Bundle mBundle) throws RemoteException {
        try {
            Bundle bundle = mBundle;

            if (bundle != null && !bundle.isEmpty()) {
                // 卸载程序包名
                String packageName = bundle.getString("packageName");

                try {
                    AppManager appManager = new AppManager(mContext);
                    appManager.setOnPackagedObserver(installCallBack);
                    // 卸载apk
                    appManager.uninstallPackage(packageName);
                } catch (NoSuchMethodException e) {
                    LogUtils.i(MyApplication.TAG, "卸载异常");
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    LogUtils.i(MyApplication.TAG, "卸载异常");
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    LogUtils.i(MyApplication.TAG, "卸载异常");
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            LogUtils.i(MyApplication.TAG, "卸载异常");
        }
    }

    @Override
    public Bundle doGetDVRInfo() throws RemoteException {

        Bundle bundle = new Bundle();
        bundle.putString("DVRDeviceVersion", Utils.deviceVersion);
        bundle.putString("DVRCardName", Utils.cardName);

        return bundle;
//        MyApplication.mDvrManager.mDvrCallBack.doDvrInfo(bundle);
    }

    @Override
    public void doFace(Bundle mBundle) throws RemoteException {
        if (mBundle != null && !mBundle.isEmpty()){
            CamService.FaceStatus = mBundle.getInt("FaceStatus", 0);
        }
    }

    @Override
    public int doFileExists(Bundle mBundle) throws RemoteException {
        String filePath = mBundle.getString("FilePath");
        if (!filePath.isEmpty()){
            File file = new File(filePath);

            if (file.exists()) {
                return 1;
            } else {
                file = new File(filePath.replaceAll(Utils.getPath1(), Utils.getPath2()));
                if (file.exists()) {
                    return 1;
                }else {
                    return -1;
                }
            }
        }else {
            return -1;
        }
    }

    @Override
    public void doVedioPara(Bundle mBundle) throws RemoteException {
        int flag = mBundle.getInt("flag", -1);              //标记   0：不标记   1：标记   -1：不设置
        int lock = mBundle.getInt("lock", -1);              //锁存   0：不锁存   1：锁存   -1：不设置
        int width1 = mBundle.getInt("width1", -1);          //通道1录像宽   -1：不设置
        int height1 = mBundle.getInt("height1", -1);        //通道1录像高   -1：不设置
        int width2 = mBundle.getInt("width2", -1);          //通道2录像宽   -1：不设置
        int height2 = mBundle.getInt("height2", -1);        //通道2录像高   -1：不设置
        int vediosave1 = mBundle.getInt("vediosave1", -1);  //通道1存储     0：不存储   1：存储   -1：不设置
        int vediosave2 = mBundle.getInt("vediosave2", -1);  //通道2存储     0：不存储   1：存储   -1：不设置
        LogUtils.e(mBundle.toString());
        CamService.SetVideoPara(flag, lock, width1, height1, width2, height2, vediosave1, vediosave2);
    }

    /**
     * 处理报警按钮触发
     * 1、记录报警时间，拷贝3个视频文件 报警前 — 报警时 — 报警后
     * 2、抓拍，前后各三张
     * 3、录音10分钟
     * @param mBundle
     * @throws RemoteException
     */
    @Override
    public void doAlarm(Bundle mBundle) throws RemoteException {

        if (!CamService.isAlarm){
            // 打开USB电源
            Utils.writeUSBPowerFile(1);

            // 如果ACC正处于关闭状态
            if (!CamService.isACC){

                synchronized (CamService.saveFilsMIPI){
                    CamService.saveFilsMIPI.clear();
                }

                synchronized (CamService.saveFilsUSB){
                    CamService.saveFilsUSB.clear();
                }
                CamService.isAlarm = true;

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            CamService.isAlarm = true;

            new AlarmThread(mBundle).start();
        } else
            LogUtils.d("前一次报警未处理完成");

        try {
            if (mBundle != null) {
                int PZJG = mBundle.getInt("PZJG", 0);
                int PZZS = mBundle.getInt("PZZS", 1); //拍摄张数
                int Cause = mBundle.getInt("Cause", -1); //拍照原因
                ArrayList<Integer> mMedias = new ArrayList<Integer>();

                for (int id = 1; id < 3; id++){
                    mBundle.putInt("ChannclID", id);
                    for (int i = 0; i < PZZS; i++) {
                        int mediaID = MyApplication.GetMediaID();
                        mMedias.add(mediaID);
                        Bundle bundle = new Bundle(mBundle);
                        bundle.putInt("MediaID", mediaID);
                        bundle.putInt("MediaType", 0);
                        bundle.putInt("MediaCode", 0);
                        bundle.putInt("EventCode", 0);
                        bundle.putIntegerArrayList("mMedias", mMedias);

                        LogUtils.e("jpegcallback1", "开始拍照 MediaID  " + bundle.getInt("MediaID") + "   PZJG = " + PZJG + "   PZZS = " + PZZS + "   Cause = " + Cause);

                        CamParameter campr = getChanncl(id);
                        if (campr != null) {
                            CamService.isRTSP = true;
                            if (campr.DEV_TYPE == CamParameter.DEV_TYPE_MIPI)
                                CamService.lRTSPTime = System.currentTimeMillis();
                            String filename = campr.saveJpgFile(putTextCPHM, mediaID, Cause, 0);
                            bundle.putString("FilePath", filename);
                            MyApplication.photoBundles.put(mediaID, bundle);
                        } else {
                            // 通道不支持
                            bundle.putInt("Result", 2);
                            mDvrManager.mDvrCallBack.doPhoto(bundle);
                        }

                        try {
                            Thread.sleep(PZJG * 1000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }catch (Exception e){
            LogUtils.e(TAG, "doPhoto异常！！！！！");
        }
    }

    class AlarmThread extends  Thread{
        private Bundle bundle;
        // 报警文件夹限制大小 MB
        private int limitSize = 3072;
        //    private int limitSize = 80;   //测试
        // 报警时需要拷贝的文件
        private List<String> copyFiles = new ArrayList<>();

        public AlarmThread(Bundle bundle){
            this.bundle = bundle;
        }

        @Override
        public void run() {
            copyFiles.clear();

            int sizeMIPI = CamService.saveFilsMIPI.size();
            int sizeUSB = CamService.saveFilsUSB.size();

            for (int i = 0; i < sizeMIPI; i++){
                String alarmFile = CamService.saveFilsMIPI.get(i);
                if (!Utils.checkfile(alarmFile)){
                    // 如果文件正在写入，确定报警时文件
                    copyFiles.add(alarmFile);
                    LogUtils.d("添加报警时文件MIPI copyFiles.size = " + copyFiles.size());

                    if (i != 0){
                        // 确定报警前文件
                        alarmFile = CamService.saveFilsMIPI.get(i - 1);
                        copyFiles.add(alarmFile);
                        LogUtils.d("添加报警前文件MIPI copyFiles.size = " + copyFiles.size());
                    }
                    break;
                }
            }
            synchronized (CamService.saveFilsMIPI){
                CamService.saveFilsMIPI.clear();
            }

            for (int i = 0; i < sizeUSB; i++){
                String alarmFile = CamService.saveFilsUSB.get(i);
                if (!Utils.checkfile(alarmFile)){
                    // 如果文件正在写入，确定报警时文件
                    copyFiles.add(alarmFile);
                    LogUtils.d("添加报警时文件USB copyFiles.size = " + copyFiles.size());

                    if (i != 0){
                        // 确定报警前文件
                        alarmFile = CamService.saveFilsUSB.get(i - 1);
                        copyFiles.add(alarmFile);
                        LogUtils.d("添加报警前文件USB copyFiles.size = " + copyFiles.size());
                    }
                    break;
                }
            }
            synchronized (CamService.saveFilsUSB){
                CamService.saveFilsUSB.clear();
            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean mipi = true;
                    boolean usb = true;
                    long timetik= 1000 * 60 * 20;
                    long startTime = System.currentTimeMillis();

                    // 开启线程确认报警后的文件
                    while (true){
                        if (CamService.saveFilsMIPI.size() >= 1 && mipi){
                            mipi = false;
                            // 确定报警后文件
                            String alarmFile = CamService.saveFilsMIPI.get(0);
                            copyFiles.add(alarmFile);
                            LogUtils.d("添加报警后文件MIPI copyFiles.size = " + copyFiles.size());
                        }

                        if (CamService.saveFilsUSB.size() >= 1 && usb){
                            usb = false;
                            // 确定报警后文件
                            String alarmFile = CamService.saveFilsUSB.get(0);
                            copyFiles.add(alarmFile);
                            LogUtils.d("添加报警后文件USB copyFiles.size = " + copyFiles.size());
                        }

                        // 已经获取到报警后的文件或者报警时间超过了timetik 则退出循环
                        if ((!mipi && !usb) || System.currentTimeMillis() - startTime > timetik){
                            break;
                        }

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    // 确认文件是否可以拷贝
                    LogUtils.d("准备开始拷贝报警文件");
                    while (true){
                        for (int i = 0; i < copyFiles.size(); i++){
                            // 检查文件是否可以拷贝
                            String alarmPath = Utils.getPathAlarm();
                            if (!alarmPath.isEmpty()){
                                if (Utils.checkfile(copyFiles.get(i))){
                                    String srcFile = copyFiles.get(i);
                                    if (!srcFile.isEmpty()){
                                        String sdPath = Utils.getPath2();
                                        if (!sdPath.isEmpty()){
                                            String disFile = srcFile.replace(sdPath, alarmPath);
                                            // 报警文件夹大小超出限制大小需进行删除
                                            if (Utils.deleteFileAlarm(alarmPath, limitSize)){
                                                if (CopyFileUtil.copyFile(srcFile, disFile, true)){
                                                    LogUtils.d("拷贝报警文件成功 文件名 = " + disFile);
                                                    copyFiles.remove(i);
                                                    break;
                                                }
                                            }
                                        }
                                    }else{
                                        copyFiles.remove(i);
                                        break;
                                    }
                                }
                            }else{
                                copyFiles.clear();
                                break;
                            }
                        }

                        if (copyFiles.size() == 0){
                            break;
                        }

                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    CamService.isAlarm = false;
                    // ACC是否处于关闭状态
                    if (!CamService.isACC){
                        CamService.isRTSP = false;
                        CamService.isAlarm = false;

                        CamService.closeVideo();
                        // 关闭USB摄像头电源
                        Utils.writeUSBPowerFile(0);
                    }
                    LogUtils.d("结束报警文件拷贝");
                }
            }).start();
        }
    }
}
